import { ref, computed } from 'vue'

/**
 * 异步操作 Hook
 * 
 * @param {Function} asyncFn - 异步函数
 * @param {object} options - 配置选项
 * @param {boolean} options.immediate - 是否立即执行，默认 false
 * @param {any} options.defaultValue - 默认返回值
 * @param {Function} options.onSuccess - 成功回调
 * @param {Function} options.onError - 错误回调
 * 
 * @returns {object} 返回异步操作相关状态和方法
 * @returns {Ref<any>} returns.data - 异步操作返回的数据
 * @returns {Ref<boolean>} returns.loading - 是否正在加载
 * @returns {Ref<Error|null>} returns.error - 错误信息
 * @returns {function} returns.execute - 执行异步操作
 * @returns {function} returns.reset - 重置状态
 * 
 * @example
 * // 基础用法
 * const { data, loading, error, execute } = useAsync(fetchUser)
 * 
 * // 立即执行
 * const { data: users, loading } = useAsync(fetchUsers, { immediate: true })
 * 
 * // 带回调
 * const { execute: login } = useAsync(loginApi, {
 *   onSuccess: (data) => console.log('登录成功:', data),
 *   onError: (error) => console.error('登录失败:', error)
 * })
 * 
 * // 在模板中使用
 * <template>
 *   <div>
 *     <div v-if="loading">加载中...</div>
 *     <div v-else-if="error">错误: {{ error.message }}</div>
 *     <div v-else>
 *       <p>用户: {{ data?.name }}</p>
 *       <button @click="execute">重新获取</button>
 *     </div>
 *   </div>
 * </template>
 * 
 * // 实际应用场景
 * const { data: userProfile, loading, execute: refreshProfile } = useAsync(
 *   () => api.getUserProfile(userId),
 *   { immediate: true }
 * )
 * 
 * // 表单提交
 * const { loading: submitting, execute: submitForm } = useAsync(
 *   (formData) => api.submitForm(formData),
 *   {
 *     onSuccess: () => ElMessage.success('提交成功'),
 *     onError: (error) => ElMessage.error(error.message)
 *   }
 * )
 */
export function useAsync(asyncFn, options = {}) {
  const {
    immediate = false,
    defaultValue = null,
    onSuccess,
    onError
  } = options
  
  const data = ref(defaultValue)
  const loading = ref(false)
  const error = ref(null)
  
  async function execute(...args) {
    try {
      loading.value = true
      error.value = null
      const result = await asyncFn(...args)
      data.value = result
      onSuccess?.(result)
      return result
    } catch (err) {
      error.value = err
      onError?.(err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  function reset() {
    data.value = defaultValue
    loading.value = false
    error.value = null
  }
  
  // 计算属性：是否成功
  const isSuccess = computed(() => !loading.value && !error.value && data.value !== null)
  
  // 计算属性：是否失败
  const isError = computed(() => !loading.value && error.value !== null)
  
  // 如果设置了立即执行，则在组件挂载时自动执行
  if (immediate) {
    execute()
  }
  
  return {
    data,
    loading,
    error,
    execute,
    reset,
    isSuccess,
    isError
  }
} 